<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 

class Scraper
{
    // define some targets
    const TARGET_PHAGIA = 0;
    const TARGET_NHOMMUA = 1;
    const TARGET_MUACHUNG = 2;

    private $CI;        // CodeIgniter instance object

    /**
    * Constructor
    */
    public function __construct()
    {
        // get CodeIgniter instance object
        $this->CI =& get_instance();

        // load common helper
        $this->CI->load->helper('common');

        // load domparser library
        $this->CI->load->library('domparser');
    }

    /**
    * extract
    *
    * Extract data from a URL (a file or a webpage).
    * Must specify correct target (PHAGIA, NHOMMUA, MUACHUNG etc.).
    *
    * @access	public
    * @param	string
    * @param	int     use the TARGET_ constants defined in Scraper class
    * @return	array	array of Deal objects, or empty array if there is no data
    */
    public function extract($url, $target)
    {
        $web_page = get_web_page($url);

        if ($web_page['errno'] != 0 OR $web_page['http_code'] != 200)
        {
            echo 'LOADING PAGE FAIL: ' . $web_page['errno'] . ' ' . $web_page['http_code'] . '<br/>';
            return array();
        }

        // Create DOM from URL or file
        // $html = $this->CI->domparser->file_get_html($url); // why this doesn't work???
        $html = $this->CI->domparser->str_get_html($web_page['content']);        

        switch ($target) {
            case self::TARGET_PHAGIA:
                return $this->_extract_phagia($html);
            case self::TARGET_NHOMMUA:
                return $this->_extract_nhommua($html,$web_page['content']);
            case self::TARGET_MUACHUNG:
                return $this->_extract_muachung($html);
        }
    }

    /**
    * _extract
    *
    * Extract data from a DOM object with target is TARGET_PHAGIA.
    *
    * @access	private
    * @param	object  DOM
    * @return	array	array of Deal objects, or empty array if there is no data
    */
    private function _extract_phagia($html)
    {
        // Result data
        $deals = array();

        // Extract some data
        $discount_deals = $html->find('div#main_right', 0)->find('.discount_deal');

        foreach ($discount_deals as $discount_deal)
        {
            $title_link     = $discount_deal->find('a', 0);
            $url_detail     = $title_link->href;
            $title          = $title_link->plaintext;
            $actual_price   = $discount_deal->find('.tag_prices', 0)->plaintext;
            $original_price = $discount_deal->find('.orginary_prices .value', 0)->plaintext;
            $percent        = $discount_deal->find('.hiv_ico .value', 0)->plaintext;
            $url_image      = $discount_deal->find('img.today_prod_img', 0)->src;
            $bought         = $discount_deal->find('.btnview .bold', 0);
            $bought         = $bought == NULL ? -1 : $bought->plaintext;

            $deal = new Deal();
            $deal->urlDetail        = trim($url_detail);
            $deal->title            = trim($title);
            $deal->priceActual      = formatMoney(getNumberOnly($actual_price));
            $deal->priceOriginal    = formatMoney(getNumberOnly($original_price));
            $deal->percent          = getNumberOnly($percent);
            $deal->urlImage         = trim($url_image);            
            $deal->peopleBought     = getNumberOnly($bought);

            $deals[] = $deal;
        }

        return $deals;
    }

    /**
    * _extract
    *
    * Extract data from a DOM object with target is TARGET_NHOMMUA.
    *
    * @access	private
    * @param	object  DOM
    * @return	array	array of Deal objects, or empty array if there is no data
    */
    private function _extract_nhommua($html, $rawhtml)
    {
        // Result data
        $deals = array();

        // Extract some data
        $content_boxes = $html->find('div.aListBPLine');

        //Parse small deals on the right
        foreach ($content_boxes as $box)
        {        
            $title_link     = $box->find('a.iIELine', 0);
            if ($title_link != NULL) {                
                $title      = $title_link->plaintext;
                $url_detail = $title_link->href;
            }            

            $actual_price   = $box->find('p.pGiaTien', 0)->find('strong.styleText5',0)->plaintext;
            $original_price = $box->find('div.divPrice', 0)->find('strong.StyleTextGT', 0)->plaintext;
            $percent        = $box->find('div.div_TietKiem',0)->find('strong.styleText15',0)->plaintext;            
            $url_image      = $box->find('div.dInfoBRNew',0)->find('img',0)->src;
            $deal = new Deal();
            $deal->urlDetail        = trim($url_detail);
            $deal->title            = trim($title);
            $deal->percent          = getNumberOnly($percent);
            $deal->priceActual      = formatMoney(getNumberOnly($actual_price));
            $deal->priceOriginal    = formatMoney(getNumberOnly($original_price));
            $deal->urlImage         = trim($url_image);
            $deals[] = $deal;
        }
        //Parse BIG deal on main page
        $content_boxes = $html->find('div.div_LBodyInfo');
        foreach ($content_boxes as $box)
        {
            if (isset($box->id)) continue;  
            $title_link     = $box->find('div.div_TextInfoDay',0)->find('h2.styleText3', 0)->find('a',0);   
            if ($title_link != null)
            {
                $title = $title_link->find('p',0)->plaintext;
                $url_detail = $title_link->href;
            }
            $actual_price   = $box->find('p.pGiaTienID', 0)->find('strong.safeUp',0)->plaintext;
            $original_price = $box->find('div.divPrice', 0)->find('strong.StyleTextGT', 0)->plaintext;
            $percent        = $box->getElementsById('divTietKiem',0)->find('strong.safeUp',0)->plaintext;            
            
            //Get image link in javascript            
            $jscript = getStrBetween($rawhtml, '"link":"', '","title":');            
            $url_image = str_ireplace('\\','',$jscript);            
            $deal = new Deal();
            $deal->urlDetail        = trim($url_detail);
            $deal->title            = trim($title);
            $deal->priceActual      = formatMoney(getNumberOnly($actual_price));
            $deal->priceOriginal    = formatMoney(getNumberOnly($original_price));
            $deal->percent          = getNumberOnly($percent);
            $deal->urlImage         = trim($url_image);
            //Put deal on first of the line
            array_unshift($deals,$deal);
        }
        return $deals;
    }

    /**
    * _extract
    *
    * Extract data from a DOM object with target is TARGET_MUACHUNG.
    *
    * @access	private
    * @param	object  DOM
    * @return	array	array of Deal objects, or empty array if there is no data
    */
    private function _extract_muachung($html)
    {
        // Result data
        $deals = array();

        // Extract some data
        $content_boxes = $html->find('div.contentBoxNew');

        foreach ($content_boxes as $box)
        {
            if (isset($box->id)) continue;

            $title_link     = $box->find('.titleBoxName', 0);
            if ($title_link != NULL) {
                $title_link = $title_link->find('a', 0);
                $url_detail = $title_link->href;
                $title      = $title_link->plaintext;
            }

            $actual_price   = $box->find('div.numPrice', 0)->plaintext;
            $original_price = $box->find('div.leftBottomPrice', 0)->find('div', 0)->plaintext;
            $percent        = $box->find('center.discount', 0)->plaintext;
            $url_image      = $box->find('.mainBoxBorder', 0)->style;
            $url_image      = getStrBetween($url_image, "url('", "')");            
            $bought         = $box->find('div.numBuyer', 0)->plaintext;

            $deal = new Deal();
            $deal->urlDetail        = trim($url_detail);
            $deal->title            = trim($title);
            $deal->priceActual      = formatMoney(getNumberOnly($actual_price));
            $deal->priceOriginal    = formatMoney(getNumberOnly($original_price));
            $deal->percent          = getNumberOnly($percent);
            $deal->urlImage         = trim($url_image);
            $deal->peopleBought     = getNumberOnly($bought);

            $deals[] = $deal;

        }

        return $deals;
    }
}

/* End of file Scraper.php */
/* Location: ./application/libraries/Scraper.php */